
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:xim/business/model/session.dart';
import 'package:xim/business/model/user.dart';
import 'package:xim/common/style/colors.dart';
import 'package:xim/common/util/collection.dart';
import 'package:xim/common/util/system.dart';
import 'package:xim/http/apis.dart';
import 'package:xim/http/apis/session/session_api.dart';
import 'package:xim/http/apis/session/session_model.dart';
import 'package:xim/http/apis/user/user_model.dart';
import 'package:xim/screen/page/qr_scan_page.dart';
import 'package:xim/widget/common/state.dart';
import 'package:xim/widget/switch_widget/switch_widget.dart';

/// 聊天会话详情页面
class ChatRoomInfoPage extends StatefulWidget {
  final int sessionId;
  const ChatRoomInfoPage({Key? key, required this.sessionId}) : super(key: key);
  @override
  State<ChatRoomInfoPage> createState() => _ChatRoomInfoPageState();
}

class _ChatRoomInfoPageState extends AppBarState<ChatRoomInfoPage>
    with ShimmerState<ChatRoomInfoPage>, BrightnessModeState<ChatRoomInfoPage> {

  @override
  String get appBarTitle => "聊天消息(${userMemberList.length})";

  @override
  Color get appBarBgColor => pageBgColor.color;

  @override
  TextStyle get appBarTitleStyle => TextStyle(color: textColor.color, fontSize: 15);

  @override
  List<ModelColor> get brightnessColors => [pageBgColor,pageFgColor,textColor,borderColor];

  ModelColor pageBgColor = ModelColor(lightColor: const Color(0xfff8f8f8), darkColor: const Color(0xff111111));
  ModelColor pageFgColor = ModelColor(lightColor: const Color(0xffffffff), darkColor: const Color(0xff181818));
  ModelColor borderColor = ModelColor(lightColor: const Color(0xffececec), darkColor: const Color(0xff222222));
  ModelColor textColor = ModelColor(darkColor: Colors.white, lightColor: Colors.black);

  /// 消息栏 padding
  EdgeInsets? infoBarPadding = const EdgeInsets.symmetric(vertical: 12, horizontal: 12);
  /// 消息栏 垂直 margin
  double infoBarVerticalMargin = 8;
  /// 消息栏 border
  BorderSide get infoBarBorderSide => BorderSide(color: borderColor.color, width: 0.6);
  /// 成员框 padding
  EdgeInsets memberBoxPadding = const EdgeInsets.symmetric(vertical: 16, horizontal: 8);
  /// 成员框 margin
  EdgeInsets memberBoxMargin = const EdgeInsets.only(bottom: 18);
  /// 展示的成员上限个数
  int showMemberCount = 9;
  /// 每行展示的成员个数
  int rowMemberCount = 5;
  /// 成员框大小
  double memberBoxSize = 60;
  BoxBorder get infoBarBorder => Border.symmetric(horizontal: infoBarBorderSide);
  late List<UserInfoModel> userMemberList;
  late SessionModel sessionInfo;

  @override
  void initContextDate(context) {
    super.initContextDate(context);
    initModelColor(context);
  }

  @override
  Widget widgetBuild(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      body: Container(
        color: pageBgColor.color,
        child: Column(
          children: [
            Container(
              width: 1.sw,
              padding: memberBoxPadding,
              margin: memberBoxMargin,
              decoration: BoxDecoration(color: pageFgColor.color,),
              child: Column(
                children: [
                  GridView(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: rowMemberCount,
                        mainAxisSpacing: 18,
                        childAspectRatio: 0.95
                    ),
                    children: userMembersBox(),
                  ),
                  memberMoreHintWidget
                ],
              ),
            ),
            Column(
              children: <Widget>[
                arrowRowBar(
                  title: "会话名称",
                  hint: sessionInfo.name,
                  isShowArrowIcon: true,
                  bgColor: pageFgColor.color,
                  padding: infoBarPadding,
                  isShowBorder: true,
                  border: infoBarBorder,
                ),
                arrowRowBar(
                  onLongPress:(){
                    Clipboard.setData(ClipboardData(text: sessionInfo.id.toString()));
                    toast("会话号拷贝成功");
                  },
                  // onTap: ()=>context.push("/qr", extra: ),
                  title: "会话号与二维码",
                  hint: sessionInfo.name,
                  isShowArrowIcon: true,
                  bgColor: pageFgColor.color,
                  padding: infoBarPadding,
                  isShowBorder: true,
                  border: infoBarBorder,
                  customRightWidget: Row(
                    children: [
                      Text(sessionInfo.id.toString(), style: const TextStyle(color: Colors.grey, fontSize: 13),),
                      const SizedBox(width: 4,),
                      const Icon(Icons.qr_code, color: Colors.grey, size: 18,),
                      const SizedBox(width: 4,),
                      const Icon(Icons.arrow_forward_ios_outlined, size: 14, color: Colors.grey,)
                    ],
                  ),
                ),
                arrowRowBar(
                    title: "查询聊天记录",
                    isShowArrowIcon: true,
                    bgColor: pageFgColor.color,
                    padding: infoBarPadding,
                    isShowBorder: true,
                    border: infoBarBorder
                ),
                Column(
                  children: [disturbInfoBar,   topRoomInfoBar,   ],
                ),
                clearChatHistory,
                existRoom
              ].splitJoin(SizedBox(height: infoBarVerticalMargin,)),
            )
          ],
        ),
      ),
    );
  }

  Widget get memberMoreHintWidget => showMemberCount < userMemberList.length ? const Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      SizedBox(height: 6,),
      Text("查看更多成员"),
      SizedBox(width: 6,),
      Icon(Icons.arrow_forward_ios_outlined, size: 13, color: Colors.grey,)
    ],
  ):const SizedBox();

  Widget get disturbInfoBar => arrowRowBar(
    title: "消息免打扰",
    bgColor: pageFgColor.color,
    padding: infoBarPadding,
    isShowBorder: true,
    border: Border(top: infoBarBorderSide),
    customRightWidget: FlutterSwitch(value: true, onToggle: (bool value) {  }, height:26, width: 48,)
  );

  Widget get topRoomInfoBar => arrowRowBar(
      title: "置顶聊天",
      bgColor: pageFgColor.color,
      padding: infoBarPadding,
      isShowBorder: true,
      border: Border(bottom: infoBarBorderSide),
      customRightWidget: FlutterSwitch(value: true, onToggle: (bool value) {  }, height:26, width: 48,)
  );

  Widget get existRoom => arrowRowBar(
    isShowArrowIcon: false,
    customCenterWidget: const Text("退出该群聊", style: TextStyle(color: Colors.red, fontSize: 16),),
    bgColor: pageFgColor.color,
    padding: infoBarPadding,
    onTap: () async {
      // 退出聊天
      var res = await showDialog(context: context, builder: (ctx){
        return quitSessionAlertDialog();
      }) as bool;
      if(res){
        var respData = await SessionApi.requestQuitSession(widget.sessionId);
        if(respData.isSuccess()){
          if(context.mounted) context.go("/home");
        }
      }
    }
  );

  Widget quitSessionAlertDialog(){
    return AlertDialog(
      title: const Text("提示"),
      content: const Text("你确定要退出该群聊吗?"),
      actions: [
        TextButton(onPressed:()=>Navigator.pop(context, false), child: const Text("取消")),
        TextButton(
            onPressed:(){
              Navigator.pop(context, true);
            },
            child: const Text("确认",style: TextStyle(color: Colors.blue),)
        ),
      ],
    );
  }

  Widget get clearChatHistory => arrowRowBar(
      isShowArrowIcon: false,
      customCenterWidget: const Text("清空聊天记录", style: TextStyle(color: Colors.cyan, fontSize: 16),),
      bgColor: pageFgColor.color,
      padding: infoBarPadding
  );

  List<Widget> userMembersBox(){
    var inviteIconBox =  userMemberIcon(height: memberBoxSize, width: memberBoxSize);
    return userMemberList
        .slice(end: showMemberCount)
        .map((e) => userMember(
          e,
          width: memberBoxSize,
          height: memberBoxSize,
          textStyle: TextStyle(color: textColor.color,fontSize: 12)),
        )
        .toList().addPlus(inviteIconBox);
  }

  Widget userMemberIcon({double? height, double? width, double strokeWidth=1}){
    return Container(
      height: height,
      width: width,
      padding: const EdgeInsets.all(6),
      child: DottedBorder(
        color: Colors.grey,
        radius: const Radius.circular(12),
        dashPattern: const [4, 4, 4, 4],
        strokeWidth: strokeWidth,
        child: Center(
          child: Icon(Icons.add_outlined, size: 28, weight: 8, color: textColor.color,),
        ),
      ),
    );
  }

  Widget userMember(UserInfoModel user, {double? height, double? width, TextStyle? textStyle}){
    return SizedBox(
      height: height,
      width: width,
      child: Column(
        children: [
          ClipRRect(
              borderRadius: const BorderRadius.all(Radius.circular(8)),
              child: Image.network(user.avatar, width: 50,)
          ),
          Text(user.name.ellipsis(6, including: true), style: textStyle,)
        ],
      ),
    );
  }

  Widget getRowBar(Widget? leftWidget,Widget? rightWidget, Function()? onTap,{
    Color? bgColor,
    EdgeInsets? padding,
    BoxBorder? border,
    Widget? centerWidget,
    Function()? onLongPress,
  }){
    return GestureDetector(
      onTap: onTap,
      onLongPress: onLongPress,
      child: Container(
        padding: padding,
        decoration: BoxDecoration(
          color: bgColor,
          border: border,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            leftWidget ?? const SizedBox(),
            centerWidget ?? const SizedBox(),
            rightWidget ?? const SizedBox(),
          ],
        ),
      ),
    );
  }

  Widget arrowRowBar({
    String? title,
    String? hint,
    Function()? onTap,
    Function()? onLongPress,
    bool isShowArrowIcon=false,
    Widget? customRightWidget,
    Color? bgColor,
    EdgeInsets? padding,
    bool isShowBorder=false,
    BoxBorder? border,
    Widget? customCenterWidget,
    Widget? customLeftWidget,
  }){
    var icons = const Icon(Icons.arrow_forward_ios_outlined, size: 14, color: Colors.grey,);
    var leftWidget = customLeftWidget ?? (title!=null? Text(title, style:TextStyle(fontSize: 16, color: textColor.color),):null);
    var rightWidget = customRightWidget ?? Row(
      children: [
        if(hint != null) Text(hint, style: const TextStyle(fontSize: 13, color: Colors.grey), ),
        if (hint != null && isShowArrowIcon) const SizedBox(width: 4,),
        if( isShowArrowIcon ) icons
      ],
    );
    border = isShowBorder? border ?? const Border.symmetric(horizontal: BorderSide(color: Colors.grey)): null;
    return getRowBar(
      onLongPress:onLongPress,
      leftWidget,
      rightWidget,
      onTap,
      bgColor: bgColor,
      padding: padding,
      border: border,
      centerWidget: customCenterWidget);
  }

  @override
  Future<void> initData() async {
    var membersInfo = await SessionApi.querySessionMembers(widget.sessionId);
    var sessionInfo = await SessionApi.querySessionInfoById(widget.sessionId);
    setState(() {
      userMemberList = membersInfo;
      this.sessionInfo = sessionInfo;
    });
    return Future(() => null);
  }

}
